package com.daxilong.starchen.player.utils;

import android.content.Context;
import android.net.TrafficStats;

import java.util.Formatter;
import java.util.Locale;

public class Utils {

	private static long lastTotalRxBytes = 0;
	private static long lastTimeStamp = 0;

	public Utils() {

	}

	/**
	 * 把毫秒转换成：1:20:30这里形式
	 * @param timeMs
	 * @return
	 */
	public static String stringForTime(int timeMs) {
		// 转换成字符串的时间
		StringBuilder mFormatBuild = new StringBuilder();
		Formatter mFormatter = new Formatter(mFormatBuild, Locale.getDefault());

		int totalSeconds = timeMs / 1000;
		int seconds = totalSeconds % 60;

		int minutes = (totalSeconds / 60) % 60;

		int hours = totalSeconds / 3600;

		if (hours > 0) {
			return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds)
					.toString();
		} else {
			return mFormatter.format("%02d:%02d", minutes, seconds).toString();
		}
	}

	/**
	 * 判断是否是网络资源
	 *
	 * @param uri
	 * @return
	 */
	public static boolean isNetUri(String uri) {
		boolean result = false;
		if (uri != null) {
			if (uri.toLowerCase().startsWith("http") || uri.toLowerCase().startsWith("rtsp") || uri.toLowerCase().startsWith("mms")) {
				result = true;
			}

		}
		return result;
	}

	/**
	 * 得到网络速度
	 * @param context
	 * @return
	 */
	public static String getNetSpeed(Context context) {

		long nowTotalRxBytes = TrafficStats.getUidRxBytes(context.getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ? 0 : (TrafficStats.getTotalRxBytes() / 1024);//转为KB
		long nowTimeStamp = System.currentTimeMillis();
		long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));//毫秒转换

		lastTimeStamp = nowTimeStamp;
		lastTotalRxBytes = nowTotalRxBytes;

		String speedStr = String.valueOf(speed) + " kb/s";

		return speedStr;
	}

}
